using System;
using System.IO;
using System.Text.Json;
// It's better to make UserStore an instance class and inject ILogger via DI.
// For a static class, logging can be tricky. Using Console.Error for simplicity here.
namespace vlcplay;

public static class UserStore
{
    private static readonly string Folder = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "xhvideoplay");
    private static readonly string FilePath = Path.Combine(Folder, "user.json");

    public static string LoadUserName()
    {
        try
        {
            if (!File.Exists(FilePath))
                return string.Empty;
            var json = File.ReadAllText(FilePath);
            var obj = JsonSerializer.Deserialize<UserData>(json);
            return obj?.UserName ?? string.Empty;
        }
        catch (JsonException ex)
        {
            // Ideally, log this with a proper logger
            Console.Error.WriteLine($"[UserStore] Failed to deserialize user data from {FilePath}: {ex.Message}");
            return string.Empty;
        }
        catch (IOException ex)
        {
            Console.Error.WriteLine($"[UserStore] Failed to read user data from {FilePath}: {ex.Message}");
            return string.Empty;
        }
        catch (Exception ex) // Catch any other unexpected errors
        {
            Console.Error.WriteLine($"[UserStore] Unexpected error loading user name from {FilePath}: {ex.ToString()}");
            return string.Empty;
        }
    }

    public static void SaveUserName(string userName)
    {
        try
        {
            if (!Directory.Exists(Folder))
                Directory.CreateDirectory(Folder);
            var obj = new UserData { UserName = userName };
            var json = JsonSerializer.Serialize(obj, new JsonSerializerOptions { WriteIndented = true });
            File.WriteAllText(FilePath, json);
        }
        catch (IOException ex)
        {
            // Ideally, log this and potentially inform the user
            Console.Error.WriteLine($"[UserStore] Failed to save user data to {FilePath}: {ex.Message}");
        }
        catch (Exception ex) // Catch any other unexpected errors
        {
            Console.Error.WriteLine($"[UserStore] Unexpected error saving user name to {FilePath}: {ex.ToString()}");
            // "ignore" is risky. Consider rethrowing or notifying the user.
        }
    }

    private class UserData
    {
        public string? UserName { get; set; } // Allow UserName to be null
    }
}
